package com.maibow.controller.admin;

import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.maibow.controller.base.BaseController;
import com.maibow.entity.admin.WeixinMenu;
import com.maibow.entity.weixin.AccessToken;
import com.maibow.entity.weixin.Button;
import com.maibow.entity.weixin.CommonButton;
import com.maibow.entity.weixin.ComplexButton;
import com.maibow.entity.weixin.Menu;
import com.maibow.entity.weixin.ViewButton;
import com.maibow.service.admin.WeixinMenuService;
import com.maibow.util.HttpRequestUtils;
import com.maibow.util.PageData;
import com.maibow.util.weixin.WeixinConstants;
import com.maibow.util.weixin.WeixinUtil;

/**
 * 
 * 脉博网络后台管理系统
 * 包名：com.maibow.controller.admin
 * 文件名：ModuleController.java
 * 作者: 吴比(Wubi)
 * 时间：2015年3月28日-下午5:38:38
 * Copyright@ 2015湖南脉博网络科技有限公司-版权所有
 *
 */
@Controller
@RequestMapping(value = "/wxmenu")
public class WeixinMenuController extends BaseController {

    @Resource(name = "weixinMenuService")
    private WeixinMenuService weixinMenuService;

    /**
     * 
     * list 显示菜单列表
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping
    public ModelAndView list() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        try {
            List<WeixinMenu> moduleList = weixinMenuService.listAllParentModule();
            modelView.addObject("moduleList", moduleList);
            modelView.setViewName("system/weixin/weixin_menu_list");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }

        return modelView;
    }

    /**
     * 获取当前菜单的所有子菜单
     * 
     * @param moduleid
     * @param response
     */
    @RequestMapping(value = "/sub")
    public void getSub(@RequestParam String moduleid, HttpServletResponse response) throws Exception {
        try {
            response.setCharacterEncoding("utf-8");
            List<WeixinMenu> subModule = weixinMenuService.listSubModuleByParentId(Integer.valueOf(moduleid));
            JSONArray arr = JSONArray.fromObject(subModule);
            PrintWriter out = response.getWriter();
            String json = arr.toString();
            out.write(json);
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 
     * toAdd(请求新增菜单页面)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/toAdd")
    public ModelAndView toAdd() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        try {
            List<WeixinMenu> moduleList = weixinMenuService.listAllParentModule();
            modelView.addObject("moduleList", moduleList);
            modelView.setViewName("system/weixin/weixin_menu_add");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 
     * add(保存菜单信息)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param module
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/add")
    public ModelAndView add(WeixinMenu module) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        try {
            module.setSubsystemid(Integer.valueOf(1));
            weixinMenuService.saveModule(module);
            modelView.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            modelView.addObject("msg", "failed");
        }
        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 请求编辑菜单页面
     * 
     * @param
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public ModelAndView toEdit(String moduleid) throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            pageData.put("moduleid", Integer.valueOf(moduleid));
            pageData = weixinMenuService.getModuleById(pageData);
            List<WeixinMenu> moduleList = weixinMenuService.listAllParentModule();
            modelView.addObject("moduleList", moduleList);
            modelView.addObject("pageData", pageData);
            modelView.setViewName("system/weixin/weixin_menu_edit");
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return modelView;
    }

    /**
     * 
     * edit(保存编辑)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@return
     * 标记：@throws Exception
     * 返回值：ModelAndView
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit() throws Exception {
        ModelAndView modelView = this.getModelAndView();
        PageData pageData = new PageData();
        try {
            pageData = this.getPageData();
            String parentmoduleid = pageData.getString("parentmoduleid");
            if (null == parentmoduleid || "".equals(parentmoduleid)) {
                parentmoduleid = "0";
            }

            pageData.put("parentmoduleid", Integer.valueOf(parentmoduleid));
            pageData.put("moduleid", Integer.valueOf(pageData.get("moduleid").toString()));
            pageData = weixinMenuService.edit(pageData);
            modelView.addObject("msg", "success");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            modelView.addObject("msg", "failed");
        }

        modelView.setViewName("save_result");
        return modelView;
    }

    /**
     * 删除菜单
     * delete(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param moduleid
     * 标记：@param out
     * 标记：@throws Exception
     * 返回值：void
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/del")
    public void delete(@RequestParam String moduleid, PrintWriter out) throws Exception {
        try {
            weixinMenuService.deleteModuleById(Integer.valueOf(moduleid));
            out.write("success");
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
    }

    /**
     * 
     * generateWXMenu(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param out
     * 返回值：void
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    @RequestMapping(value = "/generateWXMenu")
    public void generateWXMenu(PrintWriter out) {
        try {
            List<WeixinMenu> moduleList = weixinMenuService.listAllParentModule();
            Button[] button = new Button[moduleList.size()];
            int key = 1;
            int i = 0;
            for (WeixinMenu menu : moduleList) {
                if (menu.getModule_type().equals("view")) {
                    ViewButton firstLayerView = new ViewButton();
                    firstLayerView.setName(menu.getModulename());
                    firstLayerView.setUrl(menu.getModuleurl());
                    firstLayerView.setType(menu.getModule_type());

                    button[i] = firstLayerView;
                } else if (menu.getModule_type().equals("no")) {
                    ComplexButton firstLayerComplexButton = new ComplexButton();
                    firstLayerComplexButton.setName(menu.getModulename());
                    Button[] sub_button = this.getSubMenu(menu);

                    // 如果这一个含有多级菜单，则设置字菜单
                    firstLayerComplexButton.setSub_button(sub_button);
                    button[i] = firstLayerComplexButton;
                } else {
                    CommonButton firstLayerCommonButton = new CommonButton();
                    firstLayerCommonButton.setName(menu.getModulename());
                    firstLayerCommonButton.setType(menu.getModule_type());
                    firstLayerCommonButton.setKey("key" + key);
                    button[i] = firstLayerCommonButton;

                    key++;
                }

                i++;
            }

            /**
             * 这是公众号xiaoqrobot目前的菜单结构，
             * 每个一级菜单都有二级菜单项<br>
             * 
             * 在某个一级菜单下没有二级菜单的情况，menu该如何定义呢？<br>
             * 比如，第三个一级菜单项不是“更多体验”，而直接是“幽默笑话”，
             * 那么menu应该这样定义：<br>
             * menu.setButton(new Button[] {
             * mainBtn1,
             * mainBtn2, btn33 });
             */
            Menu menu = new Menu();
            menu.setButton(button);

            String requestParameter = JSON.toJSONString(menu);
            logger.debug(requestParameter);
            System.out.println(requestParameter);

            WeixinUtil weixinUtil = new WeixinUtil();
            AccessToken accessToken = weixinUtil.getAccessTokenV3(WeixinConstants.CHUXIAN_PARTY_APPID, WeixinConstants.CHUXIAN_PARTY_SECRET);
            String token = accessToken.getAccessToken();

            String deleteRequestUrl = WeixinConstants.GET_WEIXIN_DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
            JSONObject deleteJson = HttpRequestUtils.httpGet(deleteRequestUrl);
            if (null != deleteJson) {
                try {
                    logger.debug("deleteJson============ " + deleteJson);
                    logger.debug("deleteJson errcode============ " + deleteJson.get("errcode").toString());
                    String errcode = deleteJson.get("errcode").toString();
                    // 如果是正常的就创建菜单
                    if (Integer.valueOf(errcode) == 0) {
                        // 创建菜单
                        String requestUrl = WeixinConstants.GET_WEIXIN_CREATE_MENU_URL.replace("ACCESS_TOKEN", token);
                        JSONObject json = HttpRequestUtils.httpPostV2(requestUrl, requestParameter);
                        if (null != json) {
                            try {
                                logger.debug("json============ " + json);
                                logger.debug("json errcode============ " + json.get("errcode").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            out.write("success");
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 
     * getSubMenu(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param menu
     * 标记：@throws Exception
     * 返回值：void
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    private Button[] getSubMenu(WeixinMenu menu) throws Exception {
        List<WeixinMenu> subModule = weixinMenuService.listSubModuleByParentId(menu.getModuleid());
        Button[] subButton = new Button[subModule.size()];

        int subKey = 1;
        int i = 0;
        for (WeixinMenu subMenu : subModule) {
            if (subMenu.getModule_type().equals("view")) {
                ViewButton firstLayerView = new ViewButton();
                firstLayerView.setName(subMenu.getModulename());
                firstLayerView.setUrl(subMenu.getModuleurl());
                firstLayerView.setType(subMenu.getModule_type());
                subButton[i] = firstLayerView;
            } else if (menu.getModule_type().equals("click")) {
                CommonButton firstLayerCommonButton = new CommonButton();
                firstLayerCommonButton.setName(subMenu.getModulename());
                firstLayerCommonButton.setType(subMenu.getModule_type());
                firstLayerCommonButton.setKey("subKey" + subKey);
                subButton[i] = firstLayerCommonButton;

                subKey++;
            } else {
                logger.debug("未设置事件类型。。。。。。。。。。。。");
            }

            i++;
        }
        return subButton;
    }

    private static Menu getMenu() {
        CommonButton btn11 = new CommonButton();
        btn11.setName("现场聊");
        btn11.setType("click");
        btn11.setKey("V1001_TODAY_MUSIC");

        ViewButton btn12 = new ViewButton();
        btn12.setName("初现转盘");
        btn12.setType("view");
        btn12.setUrl("http://w.url.cn/s/AmSVZsc");

        ViewButton btn13 = new ViewButton();
        btn13.setName("最新活动");
        btn13.setType("view");
        btn13.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx67982411e015a05f&redirect_uri=http%3A%2F%2Fwww.hnczwl.cn/maibow-global-html5/test/src/index.htm&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");

        ComplexButton mainBtn3 = new ComplexButton();
        mainBtn3.setName("送大奖");
        mainBtn3.setSub_button(new Button[] { btn12, btn13 });

        /**
         * 这是公众号xiaoqrobot目前的菜单结构，每个一级菜单都有二级菜单项<br>
         * 
         * 在某个一级菜单下没有二级菜单的情况，menu该如何定义呢？<br>
         * 比如，第三个一级菜单项不是“更多体验”，而直接是“幽默笑话”，
         * 那么menu应该这样定义：<br>
         * menu.setButton(new Button[] { mainBtn1,
         * mainBtn2, btn33 });
         */
        Menu menu = new Menu();
        menu.setButton(new Button[] { btn11, mainBtn3 });

        return menu;
    }
}
